import { eject } from "./childwin.js";
import { Flysel, flysel, Sync } from "../plugin/flysel.js";
import { RGBA } from "./tool.js";

export const defStyle = {
    backImg: "url('./upload/efff11656ba58d65b458d5924e8e7d83.jpeg')",
    backImgMin: "url('./upload/d97ee4303044a101a8cd1d8ae39f48e6c980b29e.png@942w_1572h_progressive.webp')",
    backColor: 'rgba(255, 255, 255, 0.8)',
    backColor1: 'rgba(255, 255, 255, 1)',
    fontColor: '#333333',
    fontColors: '#888888',
}

// 默认浅色
const defStyleDark = {
    backColor: 'rgba(51, 51, 51, 0.8)',
    fontColor: '#efefef',
    fontColors: '#cccccc',
}
// 默认深色
const theme = {
    backImg: new Text(),
    backImgMin: new Text(),
    backColor: new Text(),
    backColor1: new Text(),
    fontColor: new Text(),
    fontColors: new Text()
}

// 预览色板
const color_set = flysel('#childwin .color-set')
const styleSync = new Sync({}, {
    change({ key, value }) {
        theme[key] && (theme[key].textContent = value)
    }
})

/**主题 */
export const style = styleSync.proxy

styleSync.on('set', ({ key, value }) => {
    color_set.screen('[name="' + key + '"]').css('backgroundColor', value)
    if (key === 'backColor') {
        style.backColor1 = (new RGBA(value)).mergeString({ a: 1 })
    }
})
const bdStyle = localStorage.getItem('THEME_STYLE')
if (bdStyle) {
    Object.assign(style, JSON.parse(bdStyle))
} else {
    Object.assign(style, defStyle)
    if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
        eject('confirm', '检测到您使用了深色主题，\n是否立即使用推荐的配色方案', () => {
            Object.assign(style, defStyleDark)
        })
    }
}

// 恢复主题
flysel('#def-style').on('click', () => {
    Object.assign(style, defStyle)
})
flysel('#def-style-dark').on('click', () => {
    Object.assign(style, defStyleDark)
})

// 打开主题面板
const old = { ...styleSync.src }
flysel('.icon-style').on('click', () => {
    eject('style', () => {
        Object.assign(style, old)
    })
})
// 本地同步
styleSync.on('set', () => {
    localStorage.setItem('THEME_STYLE', JSON.stringify(style))
})

// 应用主题
flysel('#theme').e.append(...[
    'body {',
    'color:', theme.fontColor, ';',
    '}',
    '.fontColors{',
    'color:', theme.fontColors, ' !important;',
    '}',
    '#bgimg {',
    // 'background-image:', theme.backImg, ';',
    '}',
    '@media (max-width: 50rem) {',
    '#bgimg {',
    // theme.backImgMin,
    '}',
    '}',
    '.backColor {',
    'background-color:', theme.backColor, ';',
    '}',
    '.backColor1 {',
    'background-color:', theme.backColor1, ';',
    '}'
])